﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Central_Control.展厅
{
    /// <summary>
    /// UserControlAddPC.xaml 的交互逻辑
    /// </summary>
    public partial class UserControlAddPC : UserControl, INotifyPropertyChanged
    {
        bool isManualPage = true;
        UserControlGallery userControlGallery;
        public GalleryButtonInfo galleryButtonInfo;
        public event PropertyChangedEventHandler? PropertyChanged;
        private ObservableCollection<PCinfo> pCinfos;
        public ObservableCollection<PCinfo> PCinfos
        {
            get { return pCinfos; }

            set { pCinfos = value; OnPropertyChanged(nameof(PCinfos)); }
        }
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public UserControlAddPC(GalleryButtonInfo galleryButtonInfo, UserControlGallery userControlGallery)
        {
            this.userControlGallery = userControlGallery;
            this.galleryButtonInfo = galleryButtonInfo;
            this.DataContext = this;
            InitializeComponent();
        }

        private async Task EnumComputersAsync()
        {
            try
            {
                PCinfos = new ObservableCollection<PCinfo>();
                if (galleryButtonInfo.pcInfos != null)
                {
                    if (galleryButtonInfo.pcInfos.Count > 0)
                    {
                        for (int i = 0; i < galleryButtonInfo.pcInfos.Count; i++)
                        {
                            PCinfo ipMacData = new PCinfo { IP = galleryButtonInfo.pcInfos[i].IP, Mac = galleryButtonInfo.pcInfos[i].MAC, Name = galleryButtonInfo.pcInfos[i].Name, isAdd = galleryButtonInfo.pcInfos[i].isAdd, ID = galleryButtonInfo.pcInfos[i].ID };
                            Dispatcher.Invoke(() =>
                            {
                                // 在 UI 线程上修改集合
                                PCinfos.Add(ipMacData);
                            });
                        }
                    }

                }

                await Task.Run(() =>
                {
                    Parallel.For(1, 256, i =>
                    {
                        string ipAddress = "192.168.10." + i.ToString();

                        // 检查IP地址是否已存在于列表中
                        if (!IsIpInList(ipAddress))
                        {
                            string macAddress = GetMacAddress(ipAddress);

                            if (macAddress != "N/A")
                            {

                                PCinfo ipMacData = new PCinfo { IP = ipAddress, Mac = macAddress };

                                // 检查计算机在线状态并更新IsOnline属性
                                //bool isOnline = CheckComputerOnline(ipAddress);
                                //ipMacData.isOnline = isOnline;
                                Debug.WriteLine("ip:" + ipMacData.IP + "  |  mac:" + ipMacData.Mac + "|" + "ID:" + ipMacData.ID);
                                // 使用 Dispatcher 来确保在 UI 线程上执行
                                Dispatcher.Invoke(() =>
                                {
                                    //if (PCinfos.Count > 0)
                                    //{
                                    //    ipMacData.ID = PCinfos[PCinfos.Count - 1].ID + 1;
                                    //}
                                    //else
                                    //{
                                    //    ipMacData.ID = 0;
                                    //}
                                    // 在 UI 线程上修改集合
                                    PCinfos.Add(ipMacData);
                                });
                                // 添加到数据列表

                            }
                        }
                    });
                });


            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: " + ex.Message);
            }
        }
        private bool IsIpInList(string ipAddress)
        {
            if (galleryButtonInfo.pcInfos != null && galleryButtonInfo.pcInfos.Count > 0)
            {
                return galleryButtonInfo.pcInfos.Any(data => data.IP == ipAddress);
            }
            else
            {
                return false;
            }

        }

        private string GetMacAddress(string ipAddress)
        {
            try
            {
                IPAddress ip = IPAddress.Parse(ipAddress);
                byte[] macAddr = new byte[6];
                uint macAddrLen = (uint)macAddr.Length;

                int res = SendARP(BitConverter.ToInt32(ip.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen);
                if (res == 0)
                {
                    string macAddress = BitConverter.ToString(macAddr, 0, (int)macAddrLen);
                    return macAddress;
                }
                else
                {
                    return "N/A";
                }
            }
            catch (Exception ex)
            {
                return "N/A";
            }
        }
        private bool CheckComputerOnline(string ipAddress)
        {
            try
            {
                Ping ping = new Ping();
                PingReply reply = ping.Send(ipAddress);

                if (reply != null && reply.Status == IPStatus.Success)
                {
                    return true; // 计算机在线
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error checking computer online status: " + ex.Message);
            }

            return false; // 计算机不在线
        }

        [DllImport("iphlpapi.dll", ExactSpelling = true)]
        public static extern int SendARP(int destIp, int srcIp, byte[] macAddr, ref uint macAddrLen);


        bool CheckInputContent()
        {
            if (IPInput.Text == string.Empty || MacInput.Text == string.Empty)
            {
                MessageBox.Show("IP和Mac地址不能为空", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return true;
            }
            else
            {
                return false;
            }
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox checkBox && checkBox.DataContext is PCinfo pcInfo)
            {
                pcInfo.isAdd = true;
            }
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox checkBox && checkBox.DataContext is PCinfo pcInfo)
            {
                pcInfo.isAdd = false;
            }
        }

        private void Confrim(object sender, RoutedEventArgs e)
        {
            List<PcInfo> pcInfos = new List<PcInfo>();
            if (galleryButtonInfo.AddPcInfos == null)
            {
                galleryButtonInfo.AddPcInfos = new List<PcInfo>();
            }
            if (isManualPage)
            {
                if (CheckInputContent())
                {
                    return;
                }
                else
                {
                    PCinfo getpc = PCinfos.FirstOrDefault(pc => pc.IP == IPInput.Text);
                    if (getpc != null && getpc.isAdd)
                    {
                        MessageBox.Show("改IP设备以添加", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    else if (getpc != null && !getpc.isAdd)
                    {
                        getpc.isAdd = true;
                    }

                    PcInfo pcInfo = new PcInfo { IP = IPInput.Text, MAC = MacInput.Text, isAdd = true };
                    if (galleryButtonInfo.AddPcInfos != null && galleryButtonInfo.AddPcInfos.Count > 0)
                    {
                        pcInfo.ID = galleryButtonInfo.AddPcInfos[galleryButtonInfo.AddPcInfos.Count - 1].ID + 1;
                    }
                    else
                    {
                        pcInfo.ID = 0;
                    }
                    if (NameInput.Text == string.Empty)
                    {
                        pcInfo.Name = "未命名";
                    }
                    else
                    {
                        pcInfo.Name = NameInput.Text;
                    }
                    galleryButtonInfo.AddPcInfos.Add(pcInfo);

                }
            }
            if (PCinfos != null && PCinfos.Count > 0)
            {
                for (int i = 0; i < PCinfos.Count; i++)
                {
                    PcInfo pcInfo = new PcInfo { IP = PCinfos[i].IP, MAC = PCinfos[i].Mac, Name = PCinfos[i].Name, isAdd = PCinfos[i].isAdd };
                    pcInfos.Add(pcInfo);
                    if (PCinfos[i].isAdd)
                    {
                        PcInfo getpcinfo = galleryButtonInfo.AddPcInfos.FirstOrDefault(button => button.IP == PCinfos[i].IP);
                        if (getpcinfo == null)
                        {
                            if (galleryButtonInfo.AddPcInfos != null && galleryButtonInfo.AddPcInfos.Count > 0)
                            {
                                pcInfo.ID = galleryButtonInfo.AddPcInfos[galleryButtonInfo.AddPcInfos.Count - 1].ID + 1;
                            }
                            else
                            {
                                pcInfo.ID = 0;
                            }
                            galleryButtonInfo.AddPcInfos.Add(pcInfo);
                        }

                    }
                    else
                    {
                        if (galleryButtonInfo.AddPcInfos != null && galleryButtonInfo.AddPcInfos.Count > 0)
                        {
                            PcInfo getpcinfo = galleryButtonInfo.AddPcInfos.FirstOrDefault(button => button.IP == PCinfos[i].IP);
                            if (getpcinfo != null)
                            {
                                galleryButtonInfo.AddPcInfos.Remove(getpcinfo);
                            }
                        }

                    }
                }
            }
            GalleryButtonInfo result = MainWindow.instance.Buttons.FirstOrDefault(button => button.ID == galleryButtonInfo.ID);
            if (result != null)
            {
                result.pcInfos = pcInfos;
                result.AddPcInfos = galleryButtonInfo.AddPcInfos;
                MainWindow.instance.SaveGalleryButtonInfoToJson();
            }
            userControlGallery.InitPC();
            BackButton_Click();
        }

        private void Manual(object sender, RoutedEventArgs e)
        {
            ManualPage.Visibility = Visibility.Visible;
            AutoPage.Visibility = Visibility.Hidden;
            isManualPage = true;
        }

        private void Auto(object sender, RoutedEventArgs e)
        {
            ManualPage.Visibility = Visibility.Hidden;
            AutoPage.Visibility = Visibility.Visible;
            isManualPage = false;
            EnumComputersAsync();
        }

        private void BackButton_Click(object sender=null, RoutedEventArgs e=null)
        {
            Manual(sender, e);
            userControlGallery.CloseAddPcPlane_Click();
        }
    }

    public class PCinfo
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string IP { get; set; }
        public string Mac { get; set; }
        public bool isAdd { get; set; }
        public bool isOnline { get; set; }
    }
}

